var util = require("../../utils/util.js");
// pages/address-edit/address-edit.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        switchChecked: !1,
        region: ['请选择地区'],
        add: true,
        name: '',
        mobile: '',
        detail: '',
        openid: '',
        goodDetailId: '',
        num: '',
        tag:'',
        pickerColor:'#818181'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        const openid = wx.getStorageSync('openid');
        this.setData({
            openid
        })
        if (options.addressId) {
            this.setData({
                add: false,
                addressId: options.addressId
            });
            this.getAddressById();
        }

        this.getTagList();
    },

    //修改地址时初始数据显示
    getAddressById: function() {
        let _this = this;
        util.get(
            getApp().api.address.detail, {
                id: _this.data.addressId
            }
        ).then(
            function(res) {
                if (res.code == 200) {
                    _this.setData({
                        switchChecked: res.data.is_default_address == 1 ? true : false,
                        region: [res.data.province, res.data.city, res.data.area],
                        code: [res.data.provinceCode, res.data.cityCode, res.data.areaCode],
                        name: res.data.deliveryName,
                        mobile: res.data.deliveryMobile,
                        detail: res.data.street,
                        tag:res.data.tag
                    });
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                    return
                }
            }
        )
    },

    //删除地址
    deleteAddress: function(e) {
        let _this = this;
        util.get(
            getApp().api.address.delete, {
                id: _this.data.addressId
            }
        ).then(
            function(res) {
                if (res.code == 200) {
                    wx.showToast({
                        title: '地址删除成功', //提示的内容,
                        icon: "success", //图标,
                        //duration: 1500, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    _this.toPrevPage();
                } else {
                    wx.showToast({
                        title: '地址删除失败', //提示的内容,
                        icon: 'none',
                        image: '../../images/icon_error.png',
                        //duration: 1500, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                    return
                }
            }
        )
    },
    inputBlur: function(e) {
        var t = '{"' + e.currentTarget.dataset.name + '":"' + e.detail.value + '"}';
        this.setData(JSON.parse(t));
    },
    inputBlur2: function(e) {
        var t = '{"' + e.currentTarget.dataset.name + '":"' + e.detail.value + '"}';
        this.setData(JSON.parse(t));
    },
    bindRegionChange: function(e) {
        this.setData({
            pickerColor:'#AAACAA',
            region: e.detail.value,
            code: e.detail.code
        })
    },
    switchChange: function(e) {
        this.setData({
            switchChecked: !this.data.switchChecked
        })
    },
    getTagList(){
        var _this = this;
        const openid = wx.getStorageSync('openid');
        util.get(
            getApp().api.address.tagList,
            {openId:openid}
        ).then(
            function(res) {
                if (res.code == 200) {
                    if(res.data!=null){
                        _this.setData({
                            tagList:res.data.tagLibArray||[]
                        })
                    }else{
                        _this.setData({
                            tagList:[]
                        })
                    }

                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                    return
                }
            }
        )
    },
    toSaveAddress: function() {
        var _this = this;
        const openid = wx.getStorageSync('openid');
        if (!_this.data.name) {
            wx.showToast({
                title: '请填写收货人姓名', //提示的内容,
                icon: "none", //图标,
                //duration: 1500, //延迟时间,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1000);
            return
        }
        if (!_this.data.mobile) {
            wx.showToast({
                title: '请填写手机号码', //提示的内容,
                icon: "none", //图标,
                //duration: 1500, //延迟时间,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1000)
            return
        }
        if (_this.data.mobile.length != 11) {
            wx.showToast({
                title: '请填写正确的手机号码', //提示的内容,
                icon: "none", //图标,
                //duration: 1500, //延迟时间,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1000)
            return
        }
        if (_this.data.region.length !== 3) {
            wx.showToast({
                title: '请选择省市区', //提示的内容,
                icon: "none", //图标,
                //duration: 1500, //延迟时间,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1000);
            return
        }
        if (!_this.data.detail) {
            wx.showToast({
                title: '请填写详细地址', //提示的内容,
                icon: "none", //图标,
                //duration: 1500, //延迟时间,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1000);
            return
        }
        var data = {
            openId: _this.data.openid,
            deliveryName: _this.data.name,
            deliveryMobile: _this.data.mobile,
            provinceCode:_this.data.code[0],
            province: _this.data.region[0],
            cityCode: _this.data.code[1],
            city: _this.data.region[1],
            areaCode:_this.data.code[2],
            area: _this.data.region[2],
            townCode: '',
            town: '',
            street: _this.data.detail,
            isDefaultAddress: _this.data.switchChecked ? 1 : 2,
            tag: _this.data.tag||"",
        };
        if (_this.data.addressId) {
            data.id = _this.data.addressId;
            util.post(
                getApp().api.address.save,
                data
            ).then(
                function(res) {
                    if (res.code == 200) {
                        wx.showToast({
                            title: '地址修改成功', //提示的内容,
                            icon: "success", //图标,
                            mask: false, //显示透明蒙层，防止触摸穿透,
                        });
                        setTimeout(function() {
                            wx.hideToast();

                            _this.toPrevPage();

                        }, 1500)
                    } else {
                        wx.showToast({
                            title: res.msg, //提示的内容,
                            icon: "none", //图标,
                            //duration: 1500, //延迟时间,
                            mask: false, //显示透明蒙层，防止触摸穿透,
                        });
                        setTimeout(function() {
                            wx.hideToast();
                        }, 1500);
                        return
                    }
                }
            )

        } else {
            util.post(
                getApp().api.address.save,
                data
            ).then(
                function(res) {
                    if (res.code == 200) {
                        wx.showToast({
                            title: '地址保存成功', //提示的内容,
                            icon: "success", //图标,
                            mask: false, //显示透明蒙层，防止触摸穿透,
                        });
                        setTimeout(function() {
                            wx.hideToast();

                            _this.toPrevPage();

                        }, 1500)
                    } else {
                        wx.showToast({
                            title: res.msg, //提示的内容,
                            icon: "none", //图标,
                            mask: false, //显示透明蒙层，防止触摸穿透,
                        });
                        setTimeout(function() {
                            wx.hideToast();
                        }, 1500);
                        return
                    }
                }
            )
        }
    },
    toPrevPage:function(){
        //返回上一页，并重刷选择地址列表
        var pages = getCurrentPages();//当前页面
        var prevPage = pages[pages.length - 2];//上一页面
        prevPage.changeData();
        wx.navigateBack({//返回
            delta: 1,
            complete:()=>{getCurrentPages().splice(pages.length - 1,1)}
        })
    },
    //自动识别事件
    autoDiscern: function (e) {

        var that = this,
            text = this.data.text,
            text = text.replace(/(^\s*)|(\s*$)/g, "");

        if (text == '') {
            wx.showToast({
                title: '无法识别',
            });
            that.setData({
                name: '',
                mobile: '',
                detail: ''
            });
            return;
        }

        var regx = /(1[3|4|5|7|8][\d]{9}|0[\d]{2,3}-[\d]{7,8}|400[-]?[\d]{3}[-]?[\d]{4})/g;
        var phone_num = text.match(regx);
        if (phone_num != null) {
            var phone = text.indexOf(phone_num[0]);
        }
        var name = text.indexOf("姓名:");
        if (name >= 0) {
            var phone = text.indexOf("电话:"),
                address = text.indexOf("地址:");
            var u_name = text.substring(name + 3, phone),
                u_phone = text.substring(phone + 3, address),
                u_address = text.substring(address + 3, text.length);
            that.setData({
                name: u_name,
                mobile: u_phone,
                detail: u_address
            })
        } else if (phone >= 0) {
            var u_name = text.substring(0, phone),
                u_phone = text.substring(phone, phone + 11),
                u_address = text.substring(phone + 11, text.length);
            that.setData({
                name: u_name,
                mobile: u_phone,
                detail: u_address
            })
        } else {
            wx.showToast({
                title: '无法识别',
            });
            that.setData({
                name: '',
                mobile: '',
                detail: ''
            })
            return;
        }
    },
    resetForm:function(e){
        this.setData({
            text: "",
        })
    },
    addTag:function(e){
        var _this = this;
        if(!_this.data.tagLabel || _this.data.tagLabel===0){
            wx.showToast({
                title: "请填写标签名", //提示的内容,
                icon: "none", //图标,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1500);
            return
        }
        if(Array.isArray(_this.data.tagList)){
            if(_this.data.tagList.indexOf(_this.data.tagLabel)>-1){
                wx.showToast({
                    title: "标签名已存在，请勿重复提交",
                    icon: "none", //图标,
                    mask: false, //显示透明蒙层，防止触摸穿透,
                });
                setTimeout(function() {
                    wx.hideToast();
                }, 1500);
                return
            }
        }
        const openid = wx.getStorageSync('openid');
        util.get(
            getApp().api.address.addTag,
            {openId:openid,tag:_this.data.tagLabel}
        ).then(
            function(res) {
                if (res.code == 200) {
                    _this.getTagList();
                    _this.setData({
                        tagLabel: "",
                    })
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                    return
                }
            }
        )
    },
    chooseTag:function(e){
        let tagLabel =  e.currentTarget.dataset.tagLabel;
        console.log(tagLabel);
        this.setData({
            tag:tagLabel
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

})